/**
 * 
 */
package pt.elvis.revanweb.client.uiBinders;

import pt.elvis.revanweb.client.CustomEvents.AppUtils;
import pt.elvis.revanweb.client.CustomEvents.AuthenticationEvent;
import pt.elvis.revanweb.client.DatabaseObjects.DatabaseHelper;
import pt.elvis.revanweb.client.DatabaseObjects.MyRequestCallback;
import pt.elvis.revanweb.client.DatabaseObjects.User_data;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CaptionPanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author elvis
 *
 */
public class LoginPanel extends Composite {

	private static LoginPanelUiBinder uiBinder = GWT
			.create(LoginPanelUiBinder.class);

	interface LoginPanelUiBinder extends UiBinder<Widget, LoginPanel> {
	}

	public LoginPanel() {
		initWidget(uiBinder.createAndBindUi(this));
		fieldset.getElement().getFirstChildElement().setAttribute("align", "right");
	}
	
	Timer timer = new Timer() {
		
		@Override
		public void run() {
			Warning.setVisible(false);
			imgLoading.setVisible(false);
		}
	};
	
	@UiField
	CaptionPanel fieldset;
	
	@UiField
	Button button;
	
	@UiField
	TextBox	Username;
	
	@UiField
	PasswordTextBox Password;

	@UiField
	Label Warning;
	
	@UiField
	Image imgLoading;
	
	public LoginPanel(String firstName) {
		initWidget(uiBinder.createAndBindUi(this));
	}
	
	@UiHandler("button")
	void handleClick(ClickEvent e) {
		imgLoading.setVisible(true);
		enable_form(false);
		Username.getText().trim();
		Password.getText().trim();
		if ((Username.getText().length() < 2) || (Password.getText().length() < 2)) {
			Warning.setText("Please fill both fields");
			Warning.setVisible(true);
			timer.schedule(3000);
			enable_form(true);
			Username.setFocus(true);			
			imgLoading.setVisible(false);
		} else {
			String variavel = "username=" + Username.getText();
			variavel += "&userpassword=" + Password.getText();
			DatabaseHelper.getData_POST("getUser.php", variavel, new MyRequestCallback() {
				
				@Override
				protected void onText(String text) {
					User_data userData = parseUserData(text);
					if (userData == null) {					
						Warning.setText("Wrong Username/Password");
						Warning.setVisible(true);
						timer.schedule(3000);
						enable_form(true);
					} else {
						enable_form(false);
						AuthenticationEvent auth = new AuthenticationEvent();
						auth.setUser(userData);
						imgLoading.setVisible(false);
						AppUtils.EVENT_BUS.fireEvent(auth);
					}
				}
			});
		}
	}
	
	/**
	 * Parses data received from RPC.
	 * @param jsonData The JSON string to parse.
	 * @return Returns User_Object or null on failure.
	 */
	private User_data parseUserData(String jsonData) {		
		User_data user = null;
		JSONValue value;
		try {
			value = JSONParser.parseStrict(jsonData);
		} catch (Exception e) {
			return null;
		}
        JSONObject userObj = value.isObject();
        String result = userObj.get("result").isString().stringValue();
        if (result.equals("success")) {
            JSONArray userArray = userObj.get("user").isArray();
            if (userArray != null) {
                for (int i=0; i < userArray.size(); i++) {
                    JSONObject bookmarkObj = userArray.get(i).isObject();
                    int idUser = Integer.parseInt(bookmarkObj.get("idUser").isString().stringValue());
                    String username = bookmarkObj.get("username").isString().stringValue();
                    String userFullName = bookmarkObj.get("userFullName").isString().stringValue();
                    String userEmail = bookmarkObj.get("userEmail").isString().stringValue();
                    String sessionID = bookmarkObj.get("SESSION_ID").isString().stringValue();
                    user = new User_data(idUser, username, userFullName, userEmail, sessionID);
                }
            } else
            	return null;
        } else
        	return null;
        return user;
	}
	
	/** 
	 * @return Returns a string with the username.
	 */
	public String getUsername() {
		return Username.getText();
	}
	/** 
	 * @return Returns a string with the user's password.
	 */
	public String getPassword() {
		return Password.getText();
	}
	/**
	 * Enables or disables the login form.
	 * @param enable To enable or disable the form.
	 */
	private void enable_form(boolean enable) {
		Username.setEnabled(enable);
		Password.setEnabled(enable);
		button.setEnabled(enable);
	}
}
